"use client";
import { useRouter, usePathname } from "next/navigation";
import { useEffect, useState } from "react";
import { Layout, Menu, Button, Space, Avatar, Dropdown, Typography } from "antd";
import { useMessage } from '@/hooks/useMessage';
import { UserOutlined, LogoutOutlined, MenuFoldOutlined, MenuUnfoldOutlined } from "@ant-design/icons";
import { adminAPI } from "@/lib/api";

const { Header, Sider, Content } = Layout;
const { Text, Title } = Typography;

interface AdminLayoutProps {
  children: React.ReactNode;
}

interface MenuItem {
  key: string;
  label: string;
  path: string;
  roles: string[];
  children?: MenuItem[];
}

export default function AdminLayout({ children }: AdminLayoutProps) {
  const message = useMessage();
  const router = useRouter();
  const [roles, setRoles] = useState<string[]>([]);
  const [userInfo, setUserInfo] = useState<{ username?: string; roles?: string[] } | null>(null);
  const [collapsed, setCollapsed] = useState(false);
  const pathname = usePathname();

  useEffect(() => {
    if (typeof window !== "undefined") {
      const userInfoStr = localStorage.getItem("userInfo");
      if (userInfoStr) {
        try {
          const userData = JSON.parse(userInfoStr);
          setUserInfo(userData);
          setRoles(userData.roles || []);
          if (userData.roles && userData.roles.includes("user")) {
            router.replace("/");
          }
        } catch {
          setUserInfo(null);
          setRoles([]);
        }
      } else {
        setUserInfo(null);
        setRoles([]);
      }
    }
  }, [router]);

  // 注意：客户端的Token检查已被移除。
  // 真正的认证检查发生在API请求层面，通过axios拦截器处理401错误。
  // 如果用户未认证，任何API请求都会导致自动跳转到登录页。

  const handleLogout = async () => {
    try {
      localStorage.removeItem("userInfo");
      await adminAPI.logout();
      message.success("您已成功退出");
      // 延迟跳转，确保用户看到提示
      setTimeout(() => {
        router.replace("/admin");
      }, 500);
    } catch (error) {
      console.error("退出登录失败:", error);
      message.error("退出失败，请稍后重试");
      // 即使后端退出失败，也强制前端跳转到登录页
      setTimeout(() => {
        router.replace("/admin");
      }, 500);
    }
  };

  // 菜单定义
  const menuItems: MenuItem[] = [
    { key: "dashboard", label: "仪表盘", path: "/admin/dashboard", roles: ["admin"] },
    { key: "articles", label: "文章管理", path: "/admin/articles", roles: ["admin", "editor"] },
    { key: "cases", label: "攻略管理", path: "/admin/cases", roles: ["admin", "editor"] },
    { key: "products-list", label: "产品列表", path: "/admin/products", roles: ["admin", "editor"] },
    // {
    //   key: 'products',
    //   label: '产品管理',
    //   path: '/admin/products',
    //   roles: ['admin', 'editor'],
    //   children: [
    //     { key: 'products-list', label: '产品列表', path: '/admin/products', roles: ['admin', 'editor'] },
    //     { key: 'product-categories', label: '分类管理', path: '/admin/products/categories', roles: ['admin', 'editor'] },
    //   ]
    // },
    { key: "users", label: "用户管理", path: "/admin/users", roles: ["admin"] },
    { key: "settings", label: "系统设置", path: "/admin/settings", roles: ["admin"] },
  ];
  // 根据角色过滤菜单
  const filteredMenu = menuItems.filter(item => item.roles.some(r => roles.includes(r)));

  // 如果是普通用户，直接不渲染内容
  if (roles.includes("user")) {
    return null;
  }

  const getSelectedKey = () => {
    if (pathname.includes("/dashboard")) return "dashboard";
    if (pathname.includes("/users")) return "users";
    if (pathname.includes("/articles")) return "articles";
    if (pathname.includes("/products/categories")) return "product-categories";
    if (pathname.includes("/products")) return "products-list";
    if (pathname.includes("/cases")) return "cases";
    if (pathname.includes("/settings")) return "settings";
    return "dashboard";
  };

  const userMenuItems = [
    // {
    //   key: "profile",
    //   label: "个人资料",
    // },
    // {
    //   key: "settings",
    //   label: "设置",
    // },
    // {
    //   type: "divider" as const,
    // },
    {
      key: "logout",
      label: "退出登录",
      icon: <LogoutOutlined />,
      onClick: handleLogout,
    },
  ];

  return (
    <Layout style={{ minHeight: "100vh" }}>
      <Sider trigger={null} collapsible collapsed={collapsed} theme='dark'>
        <div
          style={{
            height: 64,
            margin: 16,
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            borderRadius: 6,
            overflow: "hidden",
          }}
        >
          {collapsed ? (
            <Title level={4} style={{ color: "#fff", margin: 0 }}>
              AIPH
            </Title>
          ) : (
            <Title level={5} style={{ color: "#fff", margin: 0, textAlign: "center", lineHeight: 1.2 }}>
              AIPH后台管理系统
            </Title>
          )}
        </div>
        <Menu
          theme='dark'
          mode='inline'
          selectedKeys={[getSelectedKey()]}
          items={filteredMenu}
          onClick={({ key, keyPath }) => {
            // 处理子菜单点击
            if (keyPath.length > 1) {
              // 这是子菜单项
              const parentKey = keyPath[keyPath.length - 1];
              const childKey = key;

              // 查找对应的路径
              const parentItem = filteredMenu.find(item => item.key === parentKey);
              if (parentItem && parentItem.children) {
                const childItem = parentItem.children.find((child: MenuItem) => child.key === childKey);
                if (childItem) {
                  router.push(childItem.path);
                }
              }
            } else {
              // 这是主菜单项
              const menuItem = filteredMenu.find(item => item.key === key);
              if (menuItem) {
                router.push(menuItem.path);
              }
            }
          }}
        />
      </Sider>
      <Layout>
        <Header
          style={{
            padding: "0 24px",
            background: "#fff",
            display: "flex",
            alignItems: "center",
            justifyContent: "space-between",
            boxShadow: "0 1px 4px rgba(0,21,41,.08)",
          }}
        >
          <Button type='text' icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />} onClick={() => setCollapsed(!collapsed)} style={{ fontSize: "16px", width: 64, height: 64 }} />
          <Space size='large'>
            {/* <Button type="text" icon={<SearchOutlined />} />
            <Button type="text" icon={<BellOutlined />} /> */}
            <Dropdown menu={{ items: userMenuItems }} placement='bottomRight'>
              <Space style={{ cursor: "pointer" }}>
                <Avatar icon={<UserOutlined />} />
                <Text>{userInfo?.username}</Text>
              </Space>
            </Dropdown>
          </Space>
        </Header>
        <Content
          style={{
            margin: "24px 16px",
            padding: 24,
            background: "#f5f5f5",
            minHeight: 280,
            borderRadius: "8px",
          }}
        >
          {children}
        </Content>
      </Layout>
    </Layout>
  );
}
